<template>
    <div>
        <el-drawer :title="title" v-model="drawerShow" 
            direction="rtl" :before-close="handleClose" :size="900"
            :close-on-click-modal="false">
            <DataTableBar :data="tableData" :columns="columns" :config="config"
                :total="total" :pages="pages" :loading="loading" PerKey="system:dict"
                @addBefore="addBefore" @editBefore="editBefore" @remove="handleDelete"
                @search="search" @reset="searchReset" 
                @currentChange="currentChange" @sizeChange="sizeChange">
                <template v-slot:dictLabel="scope">
                    <span
                        v-if="(scope.row.listClass == '' || scope.row.listClass == 'default') && (scope.row.cssClass == '' || scope.row.cssClass == null)">{{
                            scope.row.dictLabel }}</span>
                    <el-tag v-else :type="scope.row.listClass == 'primary' ? '' : scope.row.listClass"
                        :class="scope.row.cssClass">{{ scope.row.dictLabel }}</el-tag>
                </template>
                <template v-slot:status="scope">
                    <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
                </template>
            </DataTableBar>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose">关 闭</el-button>
                </div>
            </template>
        </el-drawer>
        <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="editDicDataDialogtitle" v-model="open" width="500px" append-to-body>
         <el-form ref="dataRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="字典类型">
               <el-input v-model="form.dictType" :disabled="true" />
            </el-form-item>
            <el-form-item label="数据标签" prop="dictLabel">
               <el-input v-model="form.dictLabel" placeholder="请输入数据标签" />
            </el-form-item>
            <el-form-item label="数据键值" prop="dictValue">
               <el-input v-model="form.dictValue" placeholder="请输入数据键值" />
            </el-form-item>
            <el-form-item label="显示排序" prop="dictSort">
               <el-input-number v-model="form.dictSort" controls-position="right" :min="0" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
               <el-radio-group v-model="form.status">
                    <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">
                        {{ dict.label }}
                    </el-radio>
               </el-radio-group>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
               <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button @click="cancel">取 消</el-button>
               <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
         </template>
      </el-dialog>
    </div>
</template>
<script setup>
    import { ref } from "vue"
    import DataTableBar from "@/components/DataComponents/DataTableBar.vue"
    import useDictStore from '@/store/modules/dict'
    import { optionselect as getDictOptionselect, getType } from "@/api/system/dict/type";
    import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data";
    const { proxy } = getCurrentInstance();
    const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
    const props = defineProps(['show', 'defaultValue', 'state']);
    const emit = defineEmits(['update:show', 'submit']);
    const queryParams = ref({});
    const defaultDicData = ref({});
    const title = ref('字典数据');
    const drawerShow = ref(false);
    const editDicDataDialogtitle = ref('');
    const open = ref(false);
    const form =  ref({
        dictCode: undefined,
        dictLabel: undefined,
        dictValue: undefined,
        cssClass: undefined,
        listClass: "default",
        dictSort: 0,
        status: "0",
        remark: undefined
    });
    const rules = ref({
      dictLabel: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
      dictValue: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
      dictSort: [{ required: true, message: "数据顺序不能为空", trigger: "blur" }]
   });
    const tableData = ref([]);
    const columns = ref([
        { title: '字典名称', key: 'dictType', hide: true, search: true, searchType: 'select', options: [],},
        { title: '字典编码', key: 'dictCode', align: 'center', minWidth: 100, },
        { title: '字典标签', key: 'dictLabel', align: 'center', minWidth: 120, search: true, tableCustom: true },
        { title: '字典键值', key: 'dictValue', align: 'center', minWidth: 120, },
        { title: '排序', key: 'dictSort', align: 'center', minWidth: 60, },
        { title: '状态', key: 'status', align: 'center', width: 70, search: true, searchType: 'select', options: sys_normal_disable, tableCustom: true },
        { title: '备注', key: 'remark', align: 'center', width: 120, },
    ]);
    const config = ref({
        formAddTitle: '添加字典数据',
        formEditTitle: '字典数据编辑',
        index: true,
        searchFoldHide: true,
        editCustom: true,
    });
    const total = ref(0);
    const loading = ref(false);
    const pages = ref({ page_current: 1, page_size: 10 });
    watch(() => props.show, () => {
        drawerShow.value = props.show;
        if(props.show){
            getTypes(props.defaultValue.dictId);
        }
    }, { deep: true });
    const addBefore = () => {
        editDicDataDialogtitle.value = "添加字典数据";
        form.value.dictType = queryParams.value.dictType;
        open.value = true;
    };
    const editBefore = (row) => {
        const dictCode = row.dictCode;
        getData(dictCode).then(response => {
            form.value = response.data || {};
            open.value = true;
            editDicDataDialogtitle.value = "修改字典数据";
        });
    };
    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["dataRef"].validate(valid => {
            if (valid) {
                if (form.value.dictCode != undefined) {
                        updateData(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getTablePages();
                    });
                } else {
                    addData(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getTablePages();
                    });
                }
            }
        });
    }
    /** 取消按钮 */
    function cancel() {
        open.value = false;
    }
    /** 删除按钮操作 */
    function handleDelete(row) {
        const dictCodes = row.dictCode || ids.value;
        proxy.$modal.confirm('是否确认删除字典编码为"' + dictCodes + '"的数据项？').then(function () {
            return delData(dictCodes);
        }).then(() => {
            getTablePages();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => { });
    }
    /** 查询字典类型列表 */
    function getTypeList() {
        getDictOptionselect().then(response => {
            const index = columns.value.findIndex( item => item.key == 'dictType' );
            const dicDataList = response.data || [];
            dicDataList.map(item => {
                item.label = item.dictName;
                item.value = item.dictType;
            });
            columns.value[index].options = dicDataList
        });
    }
    const currentChange = (current) => {
        pages.value.page_current = current;
        getTablePages();
    };
    const sizeChange = (size) => {
        pages.value.page_size = size;
        getTablePages();
    };
    const search = (searchParam) => {
        queryParams.value = searchParam.value;
        if(!searchParam.value.dictType){
            queryParams.value.dictType = defaultDicData.value;
        }
        getTablePages();
    }
    const searchReset = () => {
        queryParams.value = {};
        queryParams.value.dictType = defaultDicData.value;
        getTablePages();
    };
    /** 查询字典类型详细 */
    const getTypes = (dictId) => {
        getType(dictId).then(response => {
            title.value = response.data.dictName || '字典数据';
            queryParams.value.dictType = response.data.dictType;
            defaultDicData.value = response.data.dictType;
            getTablePages();
            getTypeList();
        });
    }
    /** 查询字典数据列表 */
    const getTablePages = () => {
        loading.value = true;
        listData({
            pageNum: pages.value.page_current,
            pageSize: pages.value.page_size,
            ...queryParams.value
        }).then(response => {
            tableData.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    };
    const handleClose = () => {
        drawerShow.value = false;
        emit('update:show', false);
    };
</script>